package com.project.gcsj5.controller;

import com.project.gcsj5.common.Result;
import com.project.gcsj5.mapper.userMapper;
import com.project.gcsj5.model.User;
import com.project.gcsj5.service.userService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
public class userController {

    @Autowired
    private userService service;
    @Autowired
    private userMapper mapper;

    @PostMapping("/user")
    public Result save (@RequestBody User student){
        int a =mapper.insert(student);
        if (a!=0 ){
            return Result.success(service.getUserByName(student.getName()));
        }else
        {return Result.fail();}
    }

    @DeleteMapping("/user/{id}")
    public Result remove(@PathVariable int id){
        Boolean a = service.removeById(id);
        if(a)
        {return Result.success(a);}
        else
        {return Result.fail();}
    }

    @PutMapping("/user")
    public Result updateById(@RequestBody User user){
        Boolean a = service.updateById(user);
        if(a)
        {return Result.success(a);}
        else
        {return Result.fail();}
    }

    @GetMapping("/user")
    public Result Getlist(){
        List<User> s = new ArrayList<>();
        s=service.list();
        if(s!=null)
        {return  Result.success(s);}
        else
        {return Result.fail();}
    }

    @GetMapping("/user/{name}")
    public Result GetByid(@PathVariable("name") String name){
        List<User> user = new ArrayList<>();
        user = service.getUserByName_true(name);
        if(user != null)
        {return Result.success(user);}
        else
        {return Result.fail();}
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpSession session){
        boolean flag = service.login(user.getId(),user.getPassword());
        if(flag)
        {   session.setAttribute("name",user.getName());
            return Result.success(service.getById(user.getId()));}
        else
        {return Result.fail();}
    }


}
